package abe.gui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingWorker;

import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import abe.Parser;
import abe.SearchableTreeNode;
import abe.gui.listeners.ExitListener;

public class SimpleTree extends JFrame  implements KeyListener,
ActionListener , 
PropertyChangeListener{
	JTextArea displayArea;
	JTextField typingArea;
	JScrollPane scrollPane;
	static final String newline = System.getProperty("line.separator");
	SearchableTreeNode root = null;
	JTree tree = null;
	private JProgressBar progressBar;
	SearchTask st = null;
 
	
  public static void main(String[] args) {
	  createAndShowGUI();
  }
 
  public SimpleTree(String label) {
    super(label);

  }

  /** Small routine that will make node out of the first entry
   *  in the array, then make nodes out of subsequent entries
   *  and make them child nodes of the first one. The process is
   *  repeated recursively for entries that are arrays.
   */
  
  public void initContainer(Container content){
	  FlowLayout layout  = new FlowLayout();
	  content.setLayout(layout);
  }
    
  private void addComponentsToPane() {
      
      JButton button = new JButton("Clear");
      button.addActionListener(this);
      
      typingArea = new JTextField(20);
      typingArea.addKeyListener(this);
      
      root = new Parser().parse(new File("service.log"));
      tree = new JTree(root);

      scrollPane = new JScrollPane(tree);
      scrollPane.setPreferredSize(new Dimension(375, 125));
    
      progressBar = new JProgressBar(0, 100);
      progressBar.setValue(0);
      progressBar.setStringPainted(true);
      
      getContentPane().add(typingArea, BorderLayout.PAGE_START);
      getContentPane().add(scrollPane, BorderLayout.CENTER);
      getContentPane().add(progressBar, BorderLayout.PAGE_END);
  }

  
  private static void createAndShowGUI() {
      //Create and set up the window.
	  SimpleTree frame = new SimpleTree("ABETREE");
	  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      
      //Set up the content pane.
      frame.addComponentsToPane();
      
      
      //Display the window.
      frame.pack();
      frame.setVisible(true);
  }

@Override
public void keyPressed(KeyEvent e) {
	//displayInfo(e,"keyPressed");
}

@Override
public void keyReleased(KeyEvent e) {
	//displayInfo(e,"keyReleased");
	if (e.getKeyCode()==KeyEvent.VK_ESCAPE){
		System.exit(0);
	}
	if (e.getKeyCode()==KeyEvent.VK_ENTER){
		collapseAll();
		
		String textfieldValue = typingArea.getText();
		
		st = new SearchTask();
		st.setTextfieldValue(textfieldValue);
		st.addPropertyChangeListener(this);
        st.execute();


		
	}
	
}

class SearchTask extends SwingWorker<Void, Void> {
    private String textfieldValue;

	/*
     * Main task. Executed in background thread.
     */
    @Override
    public Void doInBackground() {
        int progress = 0;        
        setProgress(0);

    	List<TreeNode[]> treePathList = new ArrayList<TreeNode[]>();
    	
    	System.out.println("Searching for :"+textfieldValue);
    	
    	root.searchAndExpand(treePathList,textfieldValue);
    	System.out.println("Search over");
    	if (treePathList.isEmpty())
    		System.out.println("Nothing found for text:"+textfieldValue);
    	int i = 1;
    	
    	System.out.println("Number of nodes to expand :"+treePathList.size());
		
    	for (TreeNode[] treeNodes : treePathList) {
    		TreePath tp = new TreePath(treeNodes);
    		SearchableTreeNode  lpc = (SearchableTreeNode)tp.getLastPathComponent();
    		if (lpc.isLeaf())
    			tree.expandPath(tp.getParentPath());
    			else
    			tree.expandPath(tp);
    		
    		
    		int progressBase100 = i *100 /treePathList.size();
    		setProgress(progressBase100);
    		i++;
    	}
              
        
        return null;
    }

    public String getTextfieldValue() {
		return textfieldValue;
	}

	public void setTextfieldValue(String textfieldValue) {
		this.textfieldValue = textfieldValue;
	}

	/*
     * Executed in event dispatching thread
     */
    @Override
    public void done() {
        progressBar.setCursor(null); //turn off the wait cursor
    }
}
 

private void collapseAll() {
	System.out.println("Collapse all");
    int row = tree.getRowCount() - 1;
    while (row >= 1) {
      tree.collapseRow(row);
      row--;
      }
    }
	 
	
 

 

@Override
public void keyTyped(KeyEvent e) {
	//displayInfo(e,"keyTyped");
	
}

@Override
public void actionPerformed(ActionEvent e) {
	// TODO Auto-generated method stub
	
}
/**
 * DEBUG function
 * @param e
 * @param keyStatus
 */
private void displayInfo(KeyEvent e, String keyStatus){
    
    //You should only rely on the key char if the event
    //is a key typed event.
    int id = e.getID();
    String keyString;
    if (id == KeyEvent.KEY_TYPED) {
        char c = e.getKeyChar();
        keyString = "key character = '" + c + "'";
    } else {
        int keyCode = e.getKeyCode();
        keyString = "key code = " + keyCode
                + " ("
                + KeyEvent.getKeyText(keyCode)
                + ")";
    }
    
    int modifiersEx = e.getModifiersEx();
    String modString = "extended modifiers = " + modifiersEx;
    String tmpString = KeyEvent.getModifiersExText(modifiersEx);
    if (tmpString.length() > 0) {
        modString += " (" + tmpString + ")";
    } else {
        modString += " (no extended modifiers)";
    }
    
    String actionString = "action key? ";
    if (e.isActionKey()) {
        actionString += "YES";
    } else {
        actionString += "NO";
    }
    
    String locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
        locationString += "standard";
    } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
        locationString += "left";
    } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
        locationString += "right";
    } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
        locationString += "numpad";
    } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
        locationString += "unknown";
    }
    StringBuffer sb = new StringBuffer();
    sb.append(keyStatus + newline
            + "    " + keyString + newline
            + "    " + modString + newline
            + "    " + actionString + newline
            + "    " + locationString + newline);
     System.out.println(sb.toString());
}

@Override
public void propertyChange(PropertyChangeEvent evt) {
	if ("progress" == evt.getPropertyName()) {
        int progress = (Integer) evt.getNewValue();
        progressBar.setValue(progress);
        
    } 
	
}
}